import {useEffect, useState} from "react";
import {ArticleRes, fetchArticleAPI} from "@/apis/list";

// 获取列表数据
function useArticleList(channelId) {
    const [articleList, setArticleList] = useState<ArticleRes>({
        results: [],
        pre_timestamp: new Date().getTime() + ""
    });

// 渲染完成后执行
    useEffect(() => {
        // 定义函数发送请求
        const getArticleList = async () => {
            try {
                const res = await fetchArticleAPI({
                    channel_id: channelId,
                    timestamp: new Date().getTime() + ""
                });

                setArticleList({
                    results: res.data.data.results,
                    pre_timestamp: res.data.data.pre_timestamp
                })
            } catch (e) {
                throw new Error("fetch Article Error")
            }
        }
        // 调用函数
        getArticleList()
    }, [channelId])

    // 无限滚动和下拉刷新
    const [hasMore, setHasMore] = useState(true)
    const loadMore = async () => {
        try {
            const res = await fetchArticleAPI({
                channel_id: channelId,
                timestamp: articleList.pre_timestamp
            });

            // 拼接新数据，存入下一次的时间戳
            setArticleList({
                results: [...articleList.results, ...res.data.data.results],
                pre_timestamp: res.data.data.pre_timestamp
            })

            // 停止监听，判断返回数据长度为0
            if (res.data.data.results.length === 0) {
                setHasMore(false)
            }

        } catch (e) {
            throw new Error("fetch Article Error")
        }
    }

    // 下拉刷新
    const onRefresh = async () => {
        try {
            const res = await fetchArticleAPI({
                channel_id: channelId,
                timestamp: articleList.pre_timestamp
            });

            // 拼接新数据，存入下一次的时间戳
            setArticleList({
                results: [...res.data.data.results, ...articleList.results],
                pre_timestamp: res.data.data.pre_timestamp
            })
        } catch (e) {
            throw new Error("fetch Article Error")
        }
    }

    return {
        articleList,
        setArticleList,
        hasMore,
        loadMore,
        onRefresh
    }
}

export {useArticleList}